//
//  NSMineViewController.m
//  Meboo
//
//  Created by kyo on 2023/12/6.
//

#import "NSMineViewController.h"
#import "KLMeCell.h"
#import "MBEditProfileViewController.h"
#import "NSVipProfileView.h"
#import "MBSettingViewController.h"
#import "NSRongYunManager.h"
#import "NSPrivateAlbumViewController.h"
@interface NSMineViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) NSVipProfileView *vipProfileView;
@property (nonatomic, strong) NSMutableArray *imageNameArr;
@property (nonatomic, strong) NSMutableArray *titleArr;
@property (nonatomic , strong) UICollectionView *collectionView;
@end

@implementation NSMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"ffffff");
    self.navigationController.navigationBarHidden = YES;
    [self setupUI];
    [[NSRongYunManager sharedManager] getRongCloudToken];
    
    [self getData];
    
    [[MBChatDataManager sharedManager] getPrivatePhoteList:^(BOOL success) {
        
    }];
    

    [MBNotificationCenter addObserver:self selector:@selector(paySuccess) name:PAY_SUCCESS_NOTIFICATION object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self resetUserInfo];
}

- (void)paySuccess {
    __WeakSelf
    [self resetUserInfo];
    [[MBMineDataManager sharedManager] getUserPrivateInfo:^(BOOL success) {
        if (success) {
            [weakSelf.vipProfileView resetData];
        }
    }];
}

- (void)resetUserInfo {
    MBUserAccount *account = [MBUserAccount defaultAccount];
    if (account.avatarUrl.length > 0) {
        if (![account.avatarUrl containsString:@"http"]) {
            account.avatarUrl = [NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com%@",account.avatarUrl];
            [MBUserAccount saveAccount:account];
        }
        [self.vipProfileView.iconImageView sd_setImageWithURL:[NSURL URLWithString:account.avatarUrl]];
    }
    
    self.vipProfileView.nameLab.text = [NSString stringWithFormat:@"%@,%@",[MBUserAccount defaultAccount].nickName,[MBUserAccount defaultAccount].age];
    
    //资料完成度百分比 刚注册即:25%  有interests没有aboutMe:50%  有aboutMe没有interests:75% 有aboutMe有interests:100%
    NSString *rateStr = @"";
    if (account.aboutMe.length > 0 && account.interests.count > 0) {
        rateStr = @"100%";
    } else if (account.aboutMe.length > 0 && account.interests.count == 0) {
        rateStr = @"75%";
    } else if (account.aboutMe.length == 0 && account.interests.count > 0) {
        rateStr = @"50%";
    } else {
        rateStr = @"25%";
    }
//    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:rateStr];
//    [str addAttribute:NSFontAttributeName value:PDBoldScale(55) range:NSMakeRange(0, rateStr.length -1)];
//    [str addAttribute:NSFontAttributeName value:PDBoldScale(40) range:NSMakeRange(rateStr.length -1, 1)];
//    self.vipProfileView.rateLab.attributedText = str;
    self.vipProfileView.rateLab.text = rateStr;
    
    if ([MBUserAccount defaultAccount].isVip) {
        self.vipProfileView.vipImageView.hidden = NO;
        self.vipProfileView.iconImageView.layer.borderWidth = 2;
    } else {
        self.vipProfileView.vipImageView.hidden = YES;
        self.vipProfileView.iconImageView.layer.borderWidth = 0;
    }
    [self.vipProfileView resetData];
}

- (void)getData {
    __WeakSelf
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [[MBMineDataManager sharedManager] getUserPrivateInfo:^(BOOL success) {
            if (success) {
                [weakSelf.vipProfileView resetData];
            }
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [[MBLoginDataManager sharedManager] getUserInfoWithCode:@"" success:^(BOOL success) {
            dispatch_group_leave(group);
        }];
    });
    
    //调度组 全部加载完成之后的回调
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf resetUserInfo];
        });
    });
}

#pragma mark - Private Method
- (void)getPrivateFCData {
    __WeakSelf
    [[MBMineDataManager sharedManager] getUserPrivateInfo:^(BOOL success) {
        if (success) {
            [weakSelf.vipProfileView resetData];
        }
    }];
}

#pragma mark - Action

//- (void)resumeAction {
//    if (self.vipLab.hidden && [self getVipEndDate].length > 0) {
//        self.vipLab.hidden = NO;
//    }
//    [[KLPaymentManager sharePaymentManager] restorePurchaase];
//}

- (void)helpCenterAction {
    //获取
    UIAlertController  *alert = [UIAlertController alertControllerWithTitle:@"Help Center" message:[NSString stringWithFormat:@"Contact us via %@ for more support, we will reply in 48 hours.",connectEmail] preferredStyle:UIAlertControllerStyleAlert];
    if ([self getIsIpad]){
        alert.popoverPresentationController.sourceView = self.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(ScreenWidth/2,ScreenHeight/2,0,0);
        alert.popoverPresentationController.permittedArrowDirections = 0;
    }
    
    
    UIAlertAction  *emailAction = [UIAlertAction actionWithTitle:@"Copy Email" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = connectEmail;
        //debugTest 自己id快速复制取值 测试使用,正式需注释
//        if ([BaseAPI isEqualToString:@"http://120.26.196.82:9104/"]) {
//            pasteboard.string = [MBUserAccount defaultAccount].chatUserId;
        NSLog(@"copy email%@",[MBUserAccount defaultAccount].chatUserId);
//        }
        [MBProgressHUD showSuccessMessage:@"copy success"];
    }];
    
    UIAlertAction  *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:emailAction];
    [alert addAction:cancelAction];
    [self.currentViewController presentViewController:alert animated:YES completion:nil];
}

#pragma mark -- collectionView  delegate datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.titleArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KLMeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"KLMeCell" forIndexPath:indexPath];
    cell.titleStr = self.titleArr[indexPath.row];
    cell.iconImageView.image = ImageWithName(self.imageNameArr[indexPath.row]);
    return cell;
}

//设置每个section的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(MBHeightScale(10), MBWidthScale(0), MBHeightScale(10), MBWidthScale(0));
}

//设置列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return MBHeightScale(0);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(0);
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(ScreenWidth, MBHeightScale(60));
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self.navigationController pushViewController:[NSPrivateAlbumViewController new] animated:YES];
    } else if (indexPath.row == 1) {
        [self.navigationController pushViewController:[MBSettingViewController new] animated:YES];
    } else if (indexPath.row == 2) {
        [self helpCenterAction];
    }
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.vipProfileView];
    [self.vipProfileView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarHeight+MBHeightScale(195+142+84));
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.vipProfileView.mas_bottom).offset(MBHeightScale(10));
        make.right.left.bottom.equalTo(self.view);
    }];
}

#pragma mark - Setter && Getter

- (NSMutableArray *)titleArr {
    if (!_titleArr) {
        _titleArr = [NSMutableArray arrayWithArray:@[@"Private Album",@"Settings",@"Help center"]];
    }
    return _titleArr;
}

- (NSMutableArray *)imageNameArr {
    if (!_imageNameArr) {
        _imageNameArr = [NSMutableArray arrayWithArray:@[@"me_private_album",@"me_setting",@"me_helpcenter"]];
    }
    return _imageNameArr;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _collectionView.hidden = YES;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[KLMeCell class] forCellWithReuseIdentifier:@"KLMeCell"];
    }
    return _collectionView;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"mine_back_image");
    }
    return _backImageView;
}

- (NSVipProfileView *)vipProfileView {
    if (!_vipProfileView) {
        _vipProfileView = [NSVipProfileView new];
    }
    return _vipProfileView;
}
@end
